package com.example;

import com.example.dal.entity.DemoAuthor;
import com.example.dal.mapper.DemoAuthorMapper;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@MapperScan(basePackages = "com.example.dal.mapper")
public class AppPagehelper implements CommandLineRunner
{
	@Autowired
	DemoAuthorMapper demoAuthorMapper;

	@Autowired
	SqlSessionTemplate sqlSessionTemplate;

    public static void main( String[] args )
    {
        SpringApplication.run(AppPagehelper.class, args);
        System.out.println( "Hello World!" );

    }

    @Override
    public void run(String... args) throws Exception {
        PageHelper.startPage(1,50);
        List<DemoAuthor> list1= demoAuthorMapper.selectByName("demo-Mapper");
        PageHelper.clearPage();
        System.out.println(list1.get(list1.size()-1));

		PageHelper.startPage(2,50);
		List<DemoAuthor> list2= demoAuthorMapper.selectByName("demo-Mapper");
        PageHelper.clearPage();

        System.out.println(list2.get(list1.size()-1));



    }

	/**
	 * end-start=13107
	 */
	public void insertDefault(){
		Long start = System.currentTimeMillis();
		for (int i =0; i<10000;i++){
			DemoAuthor tmp = new DemoAuthor();
			tmp.setCreateTime(LocalDateTime.now());
			tmp.setModifiedTime(LocalDateTime.now());
			tmp.setName("demo-Mapper");
			demoAuthorMapper.insert(tmp);
		}

		Long end = System.currentTimeMillis();
		System.out.println("end-start="+(end-start));
	}

	/**
	 * 批量插入
	 * 批处理需要在JDBC url添加参数 rewriteBatchedStatements=true，否则还是很慢
	 * 不添加时： end-start=10876
	 * 添加时：  end-start=592
	 */
	public void insertBatch(){
		SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
		DemoAuthorMapper mapper = sqlSession.getMapper(DemoAuthorMapper.class);
		Long start = System.currentTimeMillis();
		for (int i =0; i<10000;i++){
			DemoAuthor tmp = new DemoAuthor();
			tmp.setCreateTime(LocalDateTime.now());
			tmp.setModifiedTime(LocalDateTime.now());
			tmp.setName("demo-Mapper");
			mapper.insert(tmp);
		}
		sqlSession.commit();
		Long end = System.currentTimeMillis();
		System.out.println("end-start="+(end-start));

	}
}
